﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Outlook.WorkItems.Extension.Manager;
using Outlook.WorkItems.Extension.Managers;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Globalization;
using System.Diagnostics;
using System.Drawing;
using System.IO;

namespace Outlook.WorkItems.Extension.Controls
{
    /// <summary>
    /// Manager of Favorites Team Project
    /// </summary>
    public partial class FavoritesTeamProjectForm : Form
    {
        /// <summary>
        /// Ctor
        /// </summary>
        public FavoritesTeamProjectForm()
        {
            InitializeComponent();

            InitTreeView();

            //int i = 1;
            //foreach (Image image in treeView1.ImageList.Images)
            //{
            //    image.Save(Path.Combine(@"C:\Users\blaut\Desktop\Treeview Images", i++ + ".png"));
            //}
        }

        /// <summary>
        /// Init Team Project treeview
        /// </summary>
        private void InitTreeView()
        {
            treeView1.Nodes.Clear();

            List<FavoriteTeamProject> favorites = FavoritesTeamProjectManager.GetFavoritesProjects();

            var favoritesGrouped = favorites.GroupBy(f => f.TeamServerName);
            foreach (var gp in favoritesGrouped)
            {
                TreeNode serverNode = new TreeNode(gp.Key);
                serverNode.ImageIndex = 0;
                treeView1.Nodes.Add(serverNode);
                foreach (var favorite in gp)
                {
                    TeamProjectNode node = new TeamProjectNode(favorite, false, false, false, false);
                    if (favorite.IsDefault)
                    {
                        node.ImageIndex = 2;
                        node.SelectedImageIndex = 2;
                    }
                    serverNode.Nodes.Add(node);
                }
                serverNode.ExpandAll();
            }
        }

        /// <summary>
        /// Add or remove Team Project
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                List<FavoriteTeamProject> favorites = FavoritesTeamProjectManager.GetFavoritesProjects();
                using (TeamProjectPicker picker = new TeamProjectPicker(TeamProjectPickerMode.MultiProject, false))
                {
                    foreach (var item in favorites.GroupBy(f => f.TeamServerName))
                    {
                        try
                        {
                            TfsTeamProjectCollection s = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(item.Key));
                            picker.SelectedTeamProjectCollection = s;
                            var wis = s.GetService<WorkItemStore>();
                            List<ProjectInfo> list = new List<ProjectInfo>();
                            foreach (var project in item)
                            {
                                Project p = wis.Projects[project.TeamProjectName];
                                ProjectInfo pi = new ProjectInfo(p.Uri.ToString(), p.Name, ProjectState.WellFormed);
                                list.Add(pi);
                            }
                            picker.SelectedProjects = list.ToArray();
                        }
                        catch { }
                    }


                    if (picker.ShowDialog() == DialogResult.OK)
                    {
                        var projectToDelete = favorites.Where(fav => !picker.SelectedProjects.Any(p => p.Name == fav.TeamProjectName)).Distinct().ToList();
                        var projectToAdd = picker.SelectedProjects.Where(p => !favorites.Any(fav => fav.TeamProjectName == p.Name)).Distinct().ToList();

                        foreach (var project in projectToDelete)
                        {
                            FavoritesTeamProjectManager.RemoveFavoriteProject(project);
                        }
                        foreach (var project in projectToAdd)
                        {
                            FavoriteTeamProject favorite = new FavoriteTeamProject();
                            //ProjectInfo p = project
                            favorite.TeamProjectName = project.Name;
                            favorite.TeamServerName = picker.SelectedTeamProjectCollection.Name;
                            favorite.TeamServerUri = picker.SelectedTeamProjectCollection.Uri.ToString();
                            var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(favorite.TeamServerUri));
                            IRegistration registration = tfs.GetService<IRegistration>();
                            RegistrationEntry[] entries = registration.GetRegistrationEntries(RegistrationUtilities.RosettaName);

                            foreach (ServiceInterface si in entries[0].ServiceInterfaces)
                            {
                                if (si.Name == "BaseReportsUrl")
                                    favorite.RServerAlternativeAddress = si.Url;
                                if (si.Name == "ReportsService")
                                    favorite.RServiceAlternativeAddress = si.Url;
                            }

                            RegistrationEntry[] entriesWss = registration.GetRegistrationEntries("Wss");

                            foreach (ServiceInterface si in entriesWss[0].ServiceInterfaces)
                            {
                                if (si.Name == "BaseSiteUrl")
                                    favorite.WssAlternativeAddress = si.Url;
                            }

                            FavoritesTeamProjectManager.AddFavoriteProject(favorite);
                        }
                        InitTreeView();
                    }
                }
            }
            catch (Exception ex)
            {
                using (ErrorForm frm = new ErrorForm(ex))
                {
                    frm.ShowDialog();
                }
            }
        }

        /// <summary>
        /// Define selected Team Project as Default
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            try
            {
                TeamProjectNode node = treeView1.SelectedNode as TeamProjectNode;
                if (node != null)
                {
                    FavoritesTeamProjectManager.DefineAsDefault(node.Favorite);
                }
                InitTreeView();
            }
            catch (Exception ex)
            {
                using (ErrorForm frm = new ErrorForm(ex))
                {
                    frm.ShowDialog();
                }
            }
        }

        private void areasAndIterationsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode is TeamProjectNode)
            {
                using (AreaPathIterationForm frm = new AreaPathIterationForm(((TeamProjectNode)treeView1.SelectedNode).TeamServerUrl, ((TeamProjectNode)treeView1.SelectedNode).TeamProjectName))
                {
                    frm.ShowDialog(this);
                }
            }
        }

        private void projectAlertsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode is TeamProjectNode)
            {
                string serverUrl = ((TeamProjectNode)treeView1.SelectedNode).TeamServerUrl;
                string projectName = ((TeamProjectNode)treeView1.SelectedNode).TeamProjectName;
                var server = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUrl));
                AlertSettings.ShowDialog(serverUrl, projectName, server.GetService<WorkItemStore>());
            }
        }

        private void showProjectPortalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode is TeamProjectNode)
            {
                string serverUrl = ((TeamProjectNode)treeView1.SelectedNode).TeamServerUrl;
                string projectName = ((TeamProjectNode)treeView1.SelectedNode).TeamProjectName;
                var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUrl));
                IRegistration registration = tfs.GetService<IRegistration>();
                RegistrationEntry[] entriesWss = registration.GetRegistrationEntries("Wss");
                string projectportalUrl = null;
                foreach (ServiceInterface si in entriesWss[0].ServiceInterfaces)
                {
                    if (si.Name == "BaseSiteUrl")
                        projectportalUrl = si.Url;
                }
                if (!string.IsNullOrEmpty(projectportalUrl))
                {
                    projectportalUrl = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", projectportalUrl, projectName);
                    Process.Start(projectportalUrl);
                }
            }
        }
    }
}

